package com.xx.happychatboot.middleware.springsecurity.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xx.happychatboot.base.constant.RedisConstant;
import com.xx.happychatboot.base.utils.JwtTokenUtils;
import com.xx.happychatboot.base.utils.RedisUtils;
import com.xx.happychatboot.middleware.springsecurity.domain.vo.response.AuthResponse;
import com.xx.happychatboot.middleware.springsecurity.security.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 自定义登录成功处理类
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 从 authentication 对象中获取用户的 UserDetails 实例，这里是获取用户的用户名
        UserDetail userDetail = (UserDetail) authentication.getPrincipal();

        // 通过用户名生成 Token
        String username = userDetail.getUsername();

        String accessToken = jwtTokenUtils.generateToken(username);

        // 存储token到redis中3个小时
        RedisUtils.set(RedisConstant.JWT_ACCESS + username, accessToken, RedisConstant.TOKEN_EXPIRE_DAYS, TimeUnit.HOURS);

        // 存储刷新token到redis中，时间为认证token的2倍
        String refreshToken = jwtTokenUtils.generateRefreshToken(username);
        RedisUtils.set(RedisConstant.JWT_REFRESH + username, refreshToken, RedisConstant.TOKEN_EXPIRE_DAYS * 2, TimeUnit.HOURS);

        AuthResponse authResponse = new AuthResponse(HttpServletResponse.SC_OK, "登录成功", accessToken, refreshToken, userDetail.getId());
        response.setContentType("application/json;charset=UTF-8");
        String s = new ObjectMapper().writeValueAsString(authResponse);
        response.getWriter().println(s);
    }
}
